class Storage {
  private static cache: Record<string, any> = {}
  private constructor() {}
  /**
   * @param key constant 定义的常量 KEY
   */
  static getStorage(key: string): any
  /**
   * @param key constant 定义的常量 KEY
   * @param defaultReturn 默认返回值，如果localStorage查不到数据，可以指定默认返回值
   */
  static getStorage(key: string, defaultReturn: any): any
  static getStorage(key: string, defaultReturn: any = '') {
    if (!this.cache[key]) {
      const res = localStorage.getItem(key)
      if (res == null) {
        return defaultReturn
      }
      this.cache[key] = res
    }
    try {
      return JSON.parse(this.cache[key])
    } catch (err) {
      return this.cache[key]
    }
  }

  static setStorage(key: string, val: any) {
    if (typeof val === 'object') {
      val = JSON.stringify(val)
    }
    localStorage.setItem(key, val)
    this.cache[key] = val
  }

  static remove(key: string) {
    localStorage.removeItem(key)
    if (this.cache[key]) {
      this.cache[key] = ''
    }
  }

  static removeAll() {
    localStorage.clear()
    this.cache = {}
  }
}

export default Storage
